package controller;

import entity.Staff;
import java.io.IOException;
import java.util.GregorianCalendar;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import session.StaffFacade;


/**
 *
 * @author Elise
 */
public class StaffServlet extends HttpServlet {

    @EJB
    private StaffFacade staffFacade;

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        // Process request (Perform actions, set response attributes, set path for forward dispatch)
        String pathInfo = request.getPathInfo();
        pathInfo = (pathInfo == null) ? "" : pathInfo;
        String fdPath = null;
        Pattern p = Pattern.compile("/(\\d+)(/(\\w+))?"); // matches to /id/action
        Matcher m = p.matcher(pathInfo);
        m.find();
        Long staffId;
        String action;
        try {
            staffId = Long.parseLong(m.group(1));
        } catch (Exception ex) {
            staffId = null;
        }
        try {
            action = m.group(3);
        } catch(IllegalStateException ex) {
            action = null;
        }

        ////////////////////////////////////////////////////////////////////////
        //CREATE
        if(pathInfo.equals("/new")) {
            fdPath = "/WEB-INF/view/staff/addStaff.jsp";
        }
        ////////////////////////////////////////////////////////////////////////
        //READ
        else if (pathInfo.equals("")) {
            //Generate current week
            request.setAttribute("staff", staffFacade.findAll());
            fdPath = "/WEB-INF/view/staff/default.jsp";
        }
        ////////////////////////////////////////////////////////////////////////
        else if (staffId != null && action == null) {
            //TODO: no such staff!!
            request.setAttribute("staff", staffFacade.find(staffId));
            fdPath = "/WEB-INF/view/staff/viewStaff.jsp";
        }
        ////////////////////////////////////////////////////////////////////////
        // UPDATE
        else if (staffId !=null && action.equals("edit")) {
           Staff staff = staffFacade.find(staffId);
            if(staff != null){
                request.setAttribute("staff", staff);
                fdPath = "/WEB-INF/view/staff/editStaff.jsp";
                }
            else{
                request.setAttribute("faultyId", staffId);
                fdPath = "/WEB-INF/view/staff/noSuchStaff.jsp";
            }
        }
        ////////////////////////////////////////////////////////////////////////
        //DELETE
        else if (staffId !=null && action.equals("remove")) {
            Staff staff = staffFacade.find(staffId);
            if(staff != null){
                request.setAttribute("staff", staff);
                fdPath = "/WEB-INF/view/staff/deleteStaff.jsp";
            }
            else{
                request.setAttribute("faultyId", staffId);
                fdPath = "/WEB-INF/view/staff/noSuchStaff.jsp";
            }
        }

        ////////////////////////////////////////////////////////////////////////
        // Forward dispatch
        if(fdPath == null)
            fdPath = "/WEB-INF/jspf/error/404.jsp";
        request.getRequestDispatcher(fdPath).forward(request, response);
    }
    /**
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        // Process request (Perform actions, set response attributes, set path for forward dispatch)
        String pathInfo = request.getPathInfo();
        pathInfo = (pathInfo == null) ? "" : pathInfo;
        String fdPath = null;
        Pattern p = Pattern.compile("/(\\d+)(/(\\w+))?"); // matches to /id/action
        Matcher m = p.matcher(pathInfo);
        m.find();
        Long staffId;
        String action;
        try {
            staffId = Long.parseLong(m.group(1));
        } catch (Exception ex) {
            staffId = null;
        }
        try {
            action = m.group(3);
        } catch(IllegalStateException ex) {
            action = null;
        }
        ////////////////////////////////////////////////////////////////////////
        //CREATE
        if(pathInfo.equals("/new")) {
            //Add staffto database
            Staff staff = new Staff(
                    request.getParameter("firstName"),
                    request.getParameter("lastName"));
            try {
                staffFacade.create(staff);
                request.setAttribute("staffName", staff.getName());
            } catch(Exception ex) {
                request.setAttribute("addStaffFailureFlag", true);
            }
            fdPath = "/WEB-INF/view/staff/addStaff.jsp";
        }
        ////////////////////////////////////////////////////////////////////////
        //READ
        else if (pathInfo.equals("")) {
            //Generate current week
            request.setAttribute("staff", staffFacade.findAll());
            fdPath = "/WEB-INF/view/staff/default.jsp";
        }
        ////////////////////////////////////////////////////////////////////////
        else if (staffId != null && action == null) {
            Staff staff = staffFacade.find(staffId);
            if(staff != null){
                request.setAttribute("staff", staff);
                fdPath = "/WEB-INF/view/staff/viewStaff.jsp";
            }
            else{
                request.setAttribute("faultyId", staffId);
                fdPath = "/WEB-INF/view/staff/noSuchStaff.jsp";
            }
        }
        ////////////////////////////////////////////////////////////////////////
        // UPDATE
        else if (staffId !=null && action.equals("edit")) {
            Staff staff = staffFacade.find(staffId);
            if(staff != null){
                try{
                    staff.setFirstName(request.getParameter("firstName"));
                    staff.setLastName(request.getParameter("lastName"));
                    staff.setUsername(request.getParameter("username"));
                    staff.setPassword(request.getParameter("password"));
                    // Merge new phone entity with existing record with staffId
                    staffFacade.edit(staff);
                    request.setAttribute("staffName", staff.getName());
                    request.setAttribute("staff", staff);
                    fdPath = "/WEB-INF/view/staff/editStaff.jsp";
                }
                catch (Exception ex) {
                    request.setAttribute("updateStaffFailureFlag", true);
                }
            }
            else{
                request.setAttribute("faultyId", staffId);
                fdPath = "/WEB-INF/view/staff/noSuchStaff.jsp";
            }
        }
        ////////////////////////////////////////////////////////////////////////
        //DELETE
        else if (staffId !=null && action.equals("remove")) {
            Staff staff = staffFacade.find(staffId);
            if(staff != null){
                    try {
                        staffFacade.remove(staff);
                        request.setAttribute("deletedStaffName", staff.getName());
                        fdPath = "/WEB-INF/view/staff/deleteStaff.jsp";
                    }
                    catch(Exception ex) {
                    request.setAttribute("deleteStaffFailureFlag", true);
                    }
            }
            else{
                    request.setAttribute("faultyId", staffId);
                    fdPath = "/WEB-INF/view/staff/noSuchStaff.jsp";
            }
        }

        ////////////////////////////////////////////////////////////////////////
        // Forward dispatch
        if(fdPath == null)
            fdPath = "/WEB-INF/jspf/error/404.jsp";

        request.getRequestDispatcher(fdPath).forward(request, response);
    }
    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Servlet to handle all requests with URL /staff/*";
    }// </editor-fold>
}
